package service

import (
	"gin-demo/mapper"
	"gin-demo/models"
	"gin-demo/pkg/e"
	bizcode "gin-demo/utils/bizerror"
	"github.com/jinzhu/gorm"
	"net/http"
)

var UserService userService

type userService struct {
	BaseService
}

func init() {
	UserService = userService{}
}

func (userSer userService) GetMapper() *mapper.UserMapper {
	return new(mapper.UserMapper)
}

func (userSer userService) CreateUser(user *models.User) *models.User {
	userSer.CheckParam(user)

	newUser := userSer.GetUserByUsername(user.UserName)
	if newUser != nil {
		bizcode.BizCode{}.PanicError(http.StatusOK, e.InvalidParams, "用户不存在")
	}

	userSer.GetMapper().Transaction(func(ormer *gorm.DB) {

	})
	_ = userSer.GetMapper().Insert(user)
	user.Salt = ""
	user.Password = ""
	return user
}

func (userSer userService) GetUserById(userId int, field []string) *models.User {
	user := &models.User{Id: userId, IsAble: 1}
	return userSer.GetMapper().GetUserById(user, field)
}

//更新用户
func (userSer userService) UpdateUser(user *models.User) *models.User {
	userSer.CheckParam(user)

	User := userSer.GetUserById(user.Id, []string{})
	if User == nil {
		bizcode.BizCode{}.PanicError(http.StatusOK, e.InvalidParams, "用户不存在")
	}

	User.UserName = user.UserName
	User.Sex = user.Sex
	User.Portrait = user.Portrait
	User.Topic = user.Topic
	User.Birthday = user.Birthday
	User.IsAble = 1
	if user.Description != "" {
		User.Description = user.Description
	}
	userSer.GetMapper().Update(User)
	User.Password = ""
	User.Salt = ""
	return User
}

//删除用户
func (userSer userService) DeleteUser(user *models.User) *models.User {
	newUser := userSer.GetUserById(user.Id, []string{})
	if newUser == nil {
		bizcode.BizCode{}.PanicError(http.StatusOK, e.InvalidParams, "用户不存在")
	}
	userSer.GetMapper().Update(newUser)
	return user
}

func (userSer userService) GetUserByUsername(username string) *models.User {
	user := &models.User{UserName: username, Type: 1}
	return userSer.GetMapper().GetUserByPhone(user)
}

//用户登录（用户不存在，则注册）
func (userSer userService) UserLogin(Username string) *models.User {
	User := userSer.GetUserByUsername(Username)
	if User != nil {
		return User
	} else {
		return nil
	}
}
